<template>
  <base-breadcrumb class="app-container">
    <div class="container" >
      <a-card>

        <title-name title="项目业态信息"></title-name>
        <a-row>
          <a-form-model :model="form" :rules="rules" ref="ruleForm">
            <a-col :md="8" :sm="8">
              <a-form-model-item label="项目业态" prop="formatName"
                    :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                    :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
                <BaseInput v-model="form.formatName" :disabled="type=='view'"></BaseInput>
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="状态"
                    :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                    :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }" prop="enabledStatus">
                    <a-select :getPopupContainer="getPopupContainer" style="width:100%" v-model="form.enabledStatus" :disabled="type=='view'">
                      <a-select-option :value = 1>可用</a-select-option>
                      <a-select-option :value = 0>不可用</a-select-option>
                    </a-select>
              </a-form-model-item>
            </a-col>
          </a-form-model>
        </a-row>
        <!-- <a-form-model :model="form" :rules="rules" ref="ruleForm"
                  :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                  :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
          <a-col :md="8" :sm="8">
            <a-form-model-item label="项目业态" prop="formatName">
              <BaseInput v-model="form.formatName"></BaseInput>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="状态" prop="formatName">
              <a-select v-model="form.status">
                <a-select-option value="0">可用</a-select-option>
                <a-select-option value="1">不可用</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-form-model> -->
        <div>
          <title-name title="标准WBS模板"></title-name>
          <div class="button-bar">
            <!--          <a-button type="primary" @click="action('undo')">保存信息</a-button>-->
            <!-- <a-button type="default" @click="action('undo')">回撤</a-button>
            <a-button type="default" @click="action('redo')">重做</a-button> -->
            <!--        <a-button type="primary" @click="importFromTemplate()">导入模板</a-button>-->
            <!-- <a-button type="primary" @click="addModal()">新增节点</a-button> -->
            <a-button type="primary" :disabled="type=='view'" @click="addSameNode"> 新增同级节点</a-button>
            <a-button type="primary" :disabled="type=='view'" @click="addNextNode"> 新增下级节点</a-button>
            <a-button type="default" :disabled="type=='view'" @click="action('moveUp')">上移</a-button>
            <a-button type="default" :disabled="type=='view'" @click="action('moveDown')">下移</a-button>
            <a-button type="default" :disabled="type=='view'" @click="action('outdent')">升级</a-button>
            <a-button type="default" :disabled="type=='view'" @click="action('indent')">降级</a-button>
            <!--          <a-button type="default" @click="action('undo')">回撤</a-button>-->
            <a-button type="default" :disabled="type=='view'" @click="action('del')">删除节点</a-button>
            <!-- <a-button type="primary" @click="action('moveBackward')">减一天</a-button>
            <a-button type="primary" @click="action('moveForward')">加一天</a-button>
            <a-button type="primary" @click='exportToPDFs'>下载PDF</a-button> -->
            <!-- <a-button type="primary" @click="showDrawer()">查看甘特图</a-button> -->
          <div style="float:right" class="page-btn-right-top">
            <a-button @click="submit" :disabled="type=='view'" :loading="loading" type="primary">提交</a-button>
            <a-button @click="cancel" type="primary" style="margin:0 12px">关闭</a-button>
          </div>
          </div>
        </div>
        <div class="gantt-layout">
          <!-- <a-drawer
                  title=""
                  placement="right"
                  :closable="false"
                  :z-index="10"
                  :get-container="false"
                  :visible="visible"
                  :body-style="{padding:'0'}"
                  :wrap-style="{ position: 'absolute'}"
                  width="50%"
                  :after-visible-change="afterVisibleChange"
                  @close="onClose"
          ><gantt ref="ganttCom" class="left-container"
                  :columns="ganttColumns"
                  :plugins="plugins"
                  :tasks="tasks"
                  :height="661"
                  @task-deleted="deleteTask"
                  @task-updated="logTaskUpdate"
                  @link-updated="logLinkUpdate"
                  @task-addModal="addModal"
                  @task-selected="selectTask"></gantt>
          </a-drawer> -->

          <div class="pub-table-select-count">
            <a-icon type="info-circle" theme="twoTone"/>
            <span style="margin-right: 12px">
              项目业态：<span class="totalNum">{{total.formatName }} </span> |
              节点共 ：<span class="totalNum">{{total.nodeTotal }} 项 </span> |
              一级节点共<span class="totalNum">{{ total.firstNodeNum }} 项 </span> |
              二级节点共<span class="totalNum">{{ total.secondNodeNum }} 项 </span> |
              三级节点共<span class="totalNum">{{ total.thirdNodeNum }} 项 </span> |
              周期天数<span class="totalNum">{{ total.cycleDays }} </span>
            </span>
          </div>
          <a-table v-if="tableData && tableData.length" row-key="nodeId" :scroll="{ x: 800, y: 300 }"
                   :columns="columns"
                   :defaultExpandAllRows="true"
                   :pagination="false"
                   :expandIconColumnIndex="1"
                   @expand="rowExpand"
                   :data-source="tableData"
                   :rowClassName="rowClassNames"
                   :customRow="clickRow">

              <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
            <!--阶段/类别-->
            <template slot="name" slot-scope="text, record" >
              <!-- <a-form-model style="display: inline-block;height:25px" :model="record" :rules="rules" ref="form"
                    :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                    :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
                <a-form-item prop="name" >
                  <BaseInput style="width:200px" v-if="record.nodeLevel!='3' && type=='edit'"  @change="changeName(record)" placeholder="请输入" @blur="blurData()" v-model="record.name"></BaseInput>
                  <span v-else>{{record.name}}</span>
                </a-form-item>
              </a-form-model> -->
              <div style="display:inline-block">
                  <BaseInput style="width:200px" v-if="record.nodeLevel!='3' && type=='edit'"  @change="changeName(record)" placeholder="请输入" @blur="blurData" v-model="record.name"></BaseInput>
                  <span v-else>{{record.name}}</span>
              </div>
            </template>
            <!--业务事项-->
            <template slot="businessMatters" slot-scope="text, record" >
                <BaseInput v-if="record.nodeLevel=='3' && type=='edit'"   placeholder="请输入" @blur="changeMatter" v-model="record.businessMatters"></BaseInput>
                <span v-else>{{record.businessMatters}}</span>
            </template>

            <!-- 管控级别 -->
            <template  slot="level" slot-scope="text, record" >
              <a-select :getPopupContainer="getPopupContainer" :disabled="type=='view'" v-if="record.nodeLevel=='3' && type=='edit'" :defaultValue="nodeList[0].controlLevelId" aria-placeholder="请选择" v-model="record.controlLevelName"  @change="changeLevel"  style="width:100px">
                <a-select-option v-for="item in nodeList" :key="item.controlLevelId">{{item.controlLevelName}}</a-select-option>
              </a-select>
              <span v-else>{{record.level}}</span>
            </template>
            <!-- 周期 -->
            <template slot="duration" slot-scope="text, record">
              <BaseInputNumber placeholder="请输入" v-if="record.nodeLevel=='3' && type=='edit'"   v-model="record.duration" :min="0" :max="2000"  @blur="editduration" style="width:100px" />
              <span v-else>{{record.duration}}</span>
            </template>
            <!-- 标准开始时间 -->
            <template slot="startDate" slot-scope="text, record">
              <BaseInputNumber placeholder="请输入" v-if="record.nodeLevel=='3' && type=='edit'"  v-model="record.startDate"  :min="0" :max="2000"  @blur="editstartDate" style="width:100px" />
              <span v-else>{{record.startDate}}</span>
            </template>

            <!-- 时间标准 -->
            <template slot="dateStandard" slot-scope="text, record">
              <a-select :getPopupContainer="getPopupContainer" v-if="record.nodeLevel=='3' && type=='edit'" aria-placeholder="请选择"  v-model="record.dateStandardName"  @change="changedateStandard"  style="width:100px">
                <a-select-option value="1" >
                  开工日前
                </a-select-option>
                <a-select-option value="0">
                  开工日后
                </a-select-option>
              </a-select>
              <span v-else>{{record.dateStandard}}</span>
            </template>
            <!-- 标准完成时间 -->
            <template v-if="record.nodeLevel=='3'" slot="completeDate" slot-scope="text, record">
              <span  v-if="record.completeDate<0">开工日前{{Math.abs(record.completeDate)}}天</span>
              <span v-if="record.completeDate>0">开工日后{{record.completeDate}}天</span>
              <span v-if="record.completeDate==0">开工日</span>
            </template>
            <!-- 完成标准 -->
            <template slot="completeStandard" slot-scope="text, record">
              <div style="display:flex">
                <BaseInput  type="textarea" style="width:300px;height:70px" v-if="record.nodeLevel=='3'  && type=='edit'"  @blur="changecompleteStandard" placeholder="请输入" v-model="record.completeStandard" ></BaseInput>
                <span v-else>{{record.completeStandard}}</span>
              </div>
            </template>
            <!-- 验证资料 -->
            <template slot="verifyDoc" slot-scope="text, record">
              <BaseInput  v-if="record.nodeLevel=='3'  && type=='edit'" type="textarea" style="width:300px;height:70px" @blur="changeverifyDoc" placeholder="请输入" v-model="record.verifyDoc" ></BaseInput>
              <span v-else>{{record.verifyDoc}}</span>
            </template>
            <!-- 第一责任人 -->
            <template slot="firstResponsible" slot-scope="text, record">
              <!-- <a-select  v-if="record.nodeLevel=='3'  && type=='edit'" style="width:100px" v-model="record.firstResponsible" placeholder="请选择"  @change="changeFirstRes" >
                <a-select-option v-for='item in responsList' :key="item.id" :value="item.id">{{item.name}}</a-select-option>
              </a-select> -->
              <!-- <jobs v-if="record.nodeLevel=='3'" showCheckedStrategy></jobs> -->
              <span v-if="record.firstResponsible">{{record.firstResponsible}}</span>
              <a  v-if="record.nodeLevel=='3' && record.firstResponsible"  @click="handleBind(record)">(重新选择)</a>
              <a  v-if="record.nodeLevel=='3' && !record.firstResponsible"  @click="handleBind(record)">选择第一责任人</a>
              <!-- <span v-else>{{record.firstResponsible}}</span> -->
            </template>

          </a-table>
        </div>
        <a-modal
                :visible="addVisible"
                ok-text="确 定 新 增"
                cancel-text="取 消"
                title="新增节点"
                :confirm-loading="confirmLoading"
                @ok="handleSubmit"
                @cancel="handleCancel">
          <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }" >
            <a-form-item label="新增节点位置">
              <a-select :getPopupContainer="getPopupContainer"
                      v-decorator="['note', { rules: [{ required: true, message: '请选择节点位置' }] }]"
                      placeholder="请选择节点位置"
                      @change="handleSelectChange">
                <a-select-option value="1">
                  同等级
                </a-select-option>
                <a-select-option  value="2" >
                  下级
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-modal>
      </a-card>
    </div>
    <task-template-modal @hide="importFromTemplateHide" @dataImport="onTemplateDataImport" :selectLevel="selectLevel"
                         :visible="taskTemplateVisible" />
    <modal :id="currentId" :visible="bindOrgVisible" @handleCancelFirstRes="handleCancelFirstRes" @handleOk="handleOk"></modal>

  </base-breadcrumb>
</template>
<script>
  import { gantt } from 'dhtmlx-gantt'
  import { getWbsTemplate, addSameNode, addNextNode, editNode, deleteNode ,editTemplateNode, getNodeControl ,editWbsTemplateList} from '@/api/template'
  import Gantt from '../gantt/gantt'
  import TaskTemplateModal from '../gantt/template-modal'
  import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
  import * as moment from 'moment'
  import EditableCell from './EditableCell'
  import Jobs from '@/components/TreeSelectOrganization/jobs'
  import modal from '@/components/SelectJobs' // 第一责任人
  // import Cell from './cell'
  const columns = [
    // {
    //   title: '编号',
    //   width:60,
    //   align:'center',
    //   scopedSlots: { customRender: 'serial' },
    // },
    {
      title: '编号',
      width: 60,
      customRender: (text, record, index) => {
        return record.index
      },
    },
    {
      title: '阶段/类别',
      align:'center',
      dataIndex: 'name',
      scopedSlots: { customRender: 'name' },
      width: 300,
      // customRender: (n,row) => {
      //   if(row.type!=='task'){
      //     return row.name
      //   }else{
      //     return ''
      //   }
      // }
    },
    {
      title: '业务事项',
      align:'center',
      dataIndex: 'businessMatters',
      width: 200,
      // customRender: (n,row) => {
      //   if(row.type!=='task'){
      //     const size = this.getChildrenSize(row)
      //     return `${size}个`
      //   }else{
      //     return row.matters
      //   }
      // },
      scopedSlots: { customRender: 'businessMatters' },
    },
    {
      title: '管控级别',
      dataIndex: 'level',
      align:'center',
      scopedSlots: { customRender: 'level' },
      width: 200,
    },
    {
      title: '周期',
      dataIndex: 'duration',
      align:'center',
      width: 120,
      scopedSlots: { customRender: 'duration' },
    },
    {
      title: '时间标准',
      dataIndex: 'dateStandard',
      align:'center',
      scopedSlots: { customRender: 'dateStandard' },
      width: 120,
    },
    {
      title: '标准开始时间',
      dataIndex: 'startDate',
      align:'center',
      scopedSlots: { customRender: 'startDate' },
      width: 120
    },
    {
      title: '标准完成时间',
      dataIndex: 'completeDate',
      align:'center',
      scopedSlots: { customRender: 'completeDate' },
      width: 120
    },
    {
      title: '完成标准',
      dataIndex: 'completeStandard',
      align:'center',
      scopedSlots: { customRender: 'completeStandard' },
      width: 300,
      ellipsis: true
    },
    {
      title: '验证资料',
      dataIndex: 'verifyDoc',
      align:'center',
      width: 300,
      scopedSlots: { customRender: 'verifyDoc' },
      ellipsis: true
    },
    {
      title: '第一责任人',
      width: 350,
      dataIndex: 'firstResponsible',
      align:'center',
      scopedSlots: { customRender: 'firstResponsible' },
      ellipsis: true,
    },
    // {
    //   title: '直接责任人',
    //   dataIndex: 'responsible',
    //   scopedSlots: { customRender: 'responsible' },
    //   ellipsis: true
    // },
  ]
  export default {
    name: 'DhtmlxGantt',
    components: { 
      Gantt, 
      TaskTemplateModal ,
      EditableCell,
      Jobs,
      modal
    },
    data() {
      return {
        levelOption:'',
        disabled:false,
        currentId:'',
        tableData: [],
        startDates:'',
        type:'',
        locale,
        total:{},
        tasks: { data: [], links: [] },
        columns,
        templateId:'',
        addLevel:'',
        rowSelection: {},
        responsList:[],
        resultData:{},
        saveSelectRows:[],
        bindOrgVisible:false,
        ganttColumns:[],
        firstResponsible:[],
        loading:false,
        preTasks: [],
        selectLevel:'',
        taskType: 'task',
        modalTitle: '新增节点',
        confirmLoading: false,
        nodeList:'',
        addVisible: false,
        visible:false,
        selectId:'',
        taskTemplateVisible: false,
        plugins: {
          undo: true,
          drag_timeline: true
        },
        messages: [],
        selectedTask: null,
        form:{
          enabledStatus:'',
          formatName:''
        },
        rules: {
            formatName: [{ required: true, message: '请填写项目业态名称', trigger: 'blur' }],
            enabledStatus: [{ required: true, message: '请选择状态', trigger: 'change' }],
        },
      }
    },
    beforeCreate() {
      this.form = this.$form.createForm(this, {})
    },
    created() {
      this.currentId = JSON.parse(sessionStorage.getItem('ycloud-user_info')).id
      this.templateId = this.$route.query.wbsTemplateId
      this.type=this.$route.query.type
      this.getWbsTemplateList()


      this.getNodeControl()
      localStorage.removeItem('task')
      localStorage.removeItem('link')
      this.rowSelection = this.getRowSelection()
      this.tasks.data = []
      this.tasks.links = []
      this.ganttColumns = [
        {
          name: 'sortNum', label: '序号', align: 'center',tree: true, width: 0, template: function(obj) {
            console.log(obj)
            return obj.$index + 1
          }
        }
      ]
    },
    methods: {
      // 第一责任人
      handleCancelBindOrg(val){
        // this.bindOrgVisible=val
      },
      handleCancelFirstRes(){
        this.bindOrgVisible = false
      },
      handleBind(){
        this.bindOrgVisible = true
      },
      handleOk(value){
        this.bindOrgVisible = false
        console.log(value)
        let firstRes={
          label:value.jobsSelectedName[0],
          key:value.jobsSelectedId
        }
        let data={
          templateId:this.templateId,
          nodeId:this.selectedData.nodeId,
          firstRes:firstRes
        }
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code==200){
            this.$message.success("修改成功")
          }
        })
      },
      // 提交
      submit(){
        this.loading = true
        this.$refs.ruleForm.validate(valid=>{
          if(valid){

          // if(this.form.enabledStatus=='可用'){
          //   this.form.enabledStatus=1
          // }else{
          //   this.form.enabledStatus = 0
          // }
            // this.form.formatId = this.templateId
            // this.form.name = this.form.formatName
            // this.form.status = this.form.status
            const arrList = {
              formatId:this.templateId,
              formatName:this.form.formatName,
              enabledStatus:this.form.enabledStatus
            }
            editWbsTemplateList(arrList).then(res=>{
              if(res.code=200){
                this.loading = false
                this.$message.success("提交成功")
                this.$multiTab.close(this.$route.fullpath)
              }
            })
        //   }else{
        //     this.$message.error("请将信息填写完整再提交")
          }
        })
      },
      // 关闭
      cancel(){
        this.$multiTab.close(this.$route.fullpath)
      },
      changeFirstRes(value){
        console.log(value)
        let data={
          templateId:this.templateId,
          nodeId:this.selectedData.nodeId,
          firstResponsible:value
        }
        console.log(data)
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code=='200'){
            this.$message.success("修改成功")
          }
        })
      },
      // 第一负责人
      // getOrgPost(){
      //   getOrgPost().then((res)=>{
      //     this.firstResponsible = res.data
      //   })
      // },
      getNodeControl(){
        getNodeControl().then((res)=>{
          this.nodeList = res.data
          console.log(res)
        })
      },
      changeName(value){
        console.log(value)
      },
      // 标准开始时间
      editstartDate(e){
        console.log(e.target.value)
        this.saveSelectRows.startDate = e.target.value;
        let startDate = this.saveSelectRows.startDate
        if(!startDate){
          startDate = 0
        }
        let data={
          templateId:this.templateId,
          nodeId:this.selectedData.nodeId,
          startDate:startDate
        }
        console.log(data)
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code=='200'){
            this.$message.success("修改成功")
          }
        })
      },
      // 周期
      editduration(e){
        console.log(e.target.value)
        this.saveSelectRows.duration = e.target.value;
        let duration = this.saveSelectRows.duration
        if(!duration){
          duration = 0
        }
        let data={
          templateId:this.templateId,
          nodeId:this.selectedData.nodeId,
          duration:duration
        }
        console.log(data)
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code=='200'){
            this.$message.success("修改成功")
          }
        })
      },
      // 验证资料
      changeverifyDoc(e){
        this.saveSelectRows.verifyDoc = e.target.value;
        let data = {}
        data={
          templateId:this.templateId,
          nodeId:this.selectedData.nodeId,
          verifyDoc:this.saveSelectRows.verifyDoc,
        }
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code=='200'){
            this.$message.success("修改成功")
          }
        })
      },
      // 完成标准
      changecompleteStandard(e){
        this.saveSelectRows.completeStandard = e.target.value;
        console.log(this.saveSelectRows.completeStandard)
        let data = {}
        data={
          templateId:this.templateId,
          nodeId:this.selectedData.nodeId,
          completeStandard:this.saveSelectRows.completeStandard,
        }
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code=='200'){
            this.$message.success("修改成功")
          }
        })
      },
      // 管控节点
      changeLevel(value){
        console.log(this.selectedData)
        let data={}
        data={
          templateId:this.templateId,
          nodeId:this.selectedData.nodeId,
          controlLevelId:value
        }
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code=='200'){
            this.$message.success("修改成功")
          }
        })
      },
      // 时间标准
      changedateStandard(value){
        console.log(this.selectedData)
        let data={}
        data={
          templateId:this.templateId,
          nodeId:this.selectedData.nodeId,
          dateStandard:value
        }
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code=='200'){
            this.$message.success("修改成功")
          }
        })
      },
      // 业务事项
      onCellChangeBusiness(val){
        console.log("阶段名称：",val)
        this.selectedData.name = val
      },
      // 获取模板
      getWbsTemplateList(){
        getWbsTemplate(this.templateId).then((res)=>{
          console.log(res)
          // this.form.formatName = res.data.formatName
          // this.form.status = res.data.enabledStatus
          this.form = res.data
          // if(this.form.enabledStatus === 1){
          //   this.form.enabledStatus="可用"
          // }else{
          //   this.form.enabledStatus = "不可用"
          // }
          this.tableData = []
          this.tableData = res.data.wbsNodeList
          this.total = res.data
          console.log(this.tableData)
          const tasks = gantt.getTaskByTime()
          console.log(tasks)
          const tree  = this.dataListToTree(this.tableData)
          console.log(tree)
          const dataList = this.resetDataId(tree)
          console.log(dataList)
          dataList.forEach(data => {
            console.log(data)
            gantt.addTask(this.valuesToTask(data), data.parent, data.index || 1)
          })
          const allTasks = gantt.getTaskByTime()
          console.log(allTasks)
          console.log(this.tableData )

          this.tableData = this.dataListToTree(allTasks)
          console.log(this.tableData)
          this.selectId = this.tableData[0].nodeId
          this.selectedData = this.tableData[0]
        })
      },
      // 获取模板
      getWbsTemplate(){
        getWbsTemplate(this.templateId).then((res)=>{
          this.tableData = []
          this.tableData = res.data.wbsNodeList
          this.total = res.data
          const tasks = gantt.getTaskByTime()
          const tree  = this.dataListToTree(this.tableData)
          const dataList = this.resetDataId(tree)
          dataList.forEach(data => {
            console.log(data)
            gantt.addTask(this.valuesToTask(data), data.parent, data.index || 1)
          })
          const allTasks = gantt.getTaskByTime()
          this.tableData = this.dataListToTree(allTasks)
        })
      },
      // 保存阶段名称
      blurData(e){
        console.log(e)
        this.saveSelectRows.name = e.target.value;
        console.log(this.saveSelectRows.name)
        let data = {}
        if(this.selectedData.nodeLevel==1 ||this.selectedData.nodeLevel==2){
          data={
            templateId:this.templateId,
            nodeId:this.selectedData.nodeId,
            parentId:this.selectedData.workPackId,
            workPackName:this.saveSelectRows.name,

          }
        }else{
          data={
            templateId:this.templateId,
            nodeId:this.selectedData.nodeId,
            // parentId:this.selectedData.workPackId,
            name:this.saveSelectRows.name,
          }
        }
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code=='200'){
            this.$message.success("修改成功")
          }
        })
      },
      changeMatter(e,record){
        console.log(record)
        this.saveSelectRows.businessMatters = e.target.value;
        console.log(this.saveSelectRows.businessMatters)
        let data = {}
          data={
            templateId:this.templateId,
            nodeId:this.selectedData.nodeId,
            // parentId:this.selectedData.workPackId,
            name:this.saveSelectRows.businessMatters,
          }
        editTemplateNode(data).then((res)=>{
          if(res){
            this.getWbsTemplate()
          }
          if(res.code=='200'){
            this.$message.success("修改成功")
          }
        })
      },
      handleChange(e) {
        const value = e.target.value;
        this.value = value;
        console.log(value)
      },
      // 模糊搜索
      handleSearch(value) {
        let result;
        if (!value || value.indexOf('@') >= 0) {
          result = [];
        } else {
          result = ['gmail.com', '163.com', 'qq.com'].map(domain => `${value}@${domain}`);
        }
        this.emailList = result
      },
      handleSelectChange(value) {
        console.log(value);
        if(value==1){
          this.levelOption= 1
        }else if (value==2){
          this.levelOption=2
        }
        console.log(this.levelOption)
        this.form.setFieldsValue({
          note: value,
        });
      },
      // 点击行
      clickRow(record, index){
        return {
          on: {
            click: () => {
              this.selectId = record.nodeId
              this.selectedData = record
              console.log(this.selectedData)
              this.rowClassNames(record)
              // gantt.selectTask(record.nodeId);
            }
          }
        }
      },
      onCellChange(key, dataIndex, value) {
        console.log(`${dataIndex}：${value} `);
        const dataSource = [...this.dataSource];
        const target = dataSource.find(item => item.key === key);
        if (target) {
          target[dataIndex] = value;
          this.dataSource = dataSource;
        }
      },
      onCellChangeDur(record, dataIndex, value){
        console.log(record)
        console.log(dataIndex)
        console.log(value)

        const start = record.start_date
        const endDate = gantt.calculateEndDate({
          start_date: start,
          duration: value
        })
        this.form.setFieldsValue({
          period:start.toDate()
        })


        const dataSource = [...this.dataSource];
        const target = dataSource.find(item => item.key === key);
        if (target) {
          target[dataIndex] = value;
          this.dataSource = dataSource;
        }
      },
      onClose(){
        this.visible=false
      },
      showDrawer() {
        this.visible = true;
      },
      afterVisibleChange(visible){
        if(visible){
          gantt.refreshData()
        }
      },
      getChildrenSize(p){
        let size = 0
        const getChildSize = (p)=>{
          if(p.type==='task'){
            return
          }
          p.children.forEach(c => {
            if(c.type==='task'){
              size++
            }
            getChildSize(c)
          })
        }
        getChildSize(p)
        return size
      },
      rowExpand(expanded, task){
        console.log(task)
        if(expanded){
          gantt.open(task.id)
        }else{
          gantt.close(task.id)
        }
      },
      getRowSelection() {
        return {
          columnWidth:40,
          type:'radio',
          onChange: (selectedRowKeys, selectedRows) => {
            this.selectedData = selectedRows[0]
            console.log(this.selectedData)
            gantt.selectTask(this.selectedData.nodeId);
          },
          onSelect: (record, selected, selectedRows) => {
            this.selectedData = selectedRows[0]
            console.log(this.selectedData)
            this.selectLevel= this.selectedData[0].levelType
            console.log(this.selectLevel)
            gantt.selectTask(this.selectedData.nodeId);
          },
          onSelectAll: (selected, selectedRows, changeRows) => {
            this.selectedData = selectedRows[0]
            console.log("onSelectAll"+this.selectedData)
            gantt.selectTask(this.selectedData.nodeId);
          }
        }
      },
      dataListToTree(){
        let dataList = this.tableData
        console.log(dataList)
        const dataMaps = {}
        const tree = []
        const dataListCopy = []
        dataList.forEach(data => {
          console.log(data)
          const copy = { ...data, start_date: data.startDate,parent:data.parent ,children:data.children}
          // copy.children = []
          console.log(copy.id)
          dataMaps[copy.id] = copy
          dataListCopy.push(copy)
        })
        dataListCopy.forEach(data => {
          if (data.parent) {
            const parent = dataMaps[data.parent]
            if (parent) {
              parent.children.push(data)
            } else {
              data.parent = null
              tree.push(data)
            }
          } else {
            tree.push(data)
          }
        })
        console.log(tree)
        return tree
      },
      resetDataId(tree) {
        console.log(tree)
        let index = 1
        const resetIdDataList = []
        const readTree = (children, parent) => {
          console.log(children)
          children.forEach(child => {
            console.log(child)
            index++
            if (parent) {
              child.parent = parent
            }
            console.log(child)
            if(child.children){
              if (child.children.length > 0) {
                child.id = `${new Date().getTime() + index}`
                console.log(children.id)
                resetIdDataList.push(child)
                console.log(resetIdDataList)
                readTree(child.children, child.id)
              } else {
                child.id = `${new Date().getTime() + index}`
                resetIdDataList.push(child)
              }
            }
          })
        }
        console.log(readTree)
        readTree(tree, 0)
        return resetIdDataList
      },
      onTemplateDataImport(dataList) {
        const tasks = gantt.getTaskByTime()
        const tree  = this.dataListToTree(dataList)
        dataList = this.resetDataId(tree)
        dataList.forEach(data => {
          // if (data.parentNames) {
          //   const parentNames = data.parentNames.split('{|}')
          //   parentNames.some(name => {
          //     return tasks.some(task => {
          //       if (task.name === name) {
          //         data.parent = task.id
          //         task.$open = true;
          //         gantt.updateTask(task.id)
          //         const childLength = gantt.getChildren(task.id).length
          //         data.index = childLength + 1
          //         if (!data.start_date) {
          //           data.start_date = new Date()
          //         }
          //         return true
          //       }
          //     })
          //   })
          // }
          gantt.addTask(this.valuesToTask(data), data.parent, data.index || 1)
        })
        const allTasks = gantt.getTaskByTime()
        this.tableData = this.dataListToTree(allTasks)
      },
      importFromTemplate() {
        console.log(this.selectLevel)
        // if(this.selectedData.length==0){
        //   this.$confirm({
        //     title: '提示！！',
        //     content: '请选中任务',
        //     okText: '确定',
        //     cancelText: '取消',
        //     onOk() {
        //       return false
        //     },
        //     onCancel() {
        //       return false
        //     },
        //   });

        // }
        this.taskTemplateVisible = true
      },
      importFromTemplateHide() {
        this.taskTemplateVisible = false
      },
      parentFilterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        )
      },
      onTaskTypeChange(val) {
        this.taskType = val
      },
      onChange(value, dateString) {
        const start = value[0]
        console.log(start.toDate())
        const end = value[1]
        const duration = gantt.calculateDuration({
          start_date: start.toDate(),
          end_date: end.toDate()
        })
        this.form.setFieldsValue({
          duration
        })
      },
      onDaySizeChange(value) {
        const start = this.startDates[0]
        const endDate = gantt.calculateEndDate({
          start_date: start.toDate(),
          duration: value
        })
        this.form.setFieldsValue({
          period:start.toDate()
        })
      },
      getPeriod(){
        this.startDates = this.form.getFieldValue('period')
      },
      handleCancel() {
        this.confirmLoading = false
        this.addVisible = false
      },
      valuesToTask(values) {
        console.log(values)
        return {
          id: values.id,
          parent:values.parent,
          text: values.matters||values.name,
          name: values.name,
          start_date: values.start_date,
          startDate:values.startDate||'',
          end_date:values.end_date,
          endDate:values.endDate||'',
          duration: values.duration,
          parentId: values.workPackId,
          type: values.type,
          preTask: values.preTask,
          matters: values.businessMatters,
          level: values.level,
          levelType: values.levelType,
          responsible: values.responsible,
          firstResponsible: values.firstResponsible,
          nodeLevel:values.nodeLevel,
          nodeId:values.nodeId,
          workPackId:values.workPackId
        }
      },
      // 新增同级节点
      addSameNode(){
        if(!this.selectedData){
          this.$message.error("请选择节点")
          return false
        }else{
          let _this = this
          this.$confirm({
            okText: '确定',
            cancelText: '取消',
            title: '确定新增同级节点?',
            onOk() {
              //如果选择的是一级节点
              console.log(_this.selectedData.nodeLevel)
              if(_this.selectedData.nodeLevel=='1'){
                addSameNode({templateId:_this.templateId,workPackId:_this.selectedData.workPackId}).then((res)=>{
                  if(res){
                    _this.getWbsTemplate()
                  }
                  if(res.code=='200'){
                    _this.$message.success("新增节点成功")
                    _this.resultData = res.data
                  }
                })
              } else if(_this.selectedData.nodeLevel=='2'){
                addSameNode({templateId:_this.templateId,parentId:_this.selectedData.nodeId}).then((res)=>{
                  if(res){
                    _this.getWbsTemplate()
                  }
                  if(res.code=='200'){
                    _this.$message.success("新增成功")
                  }
                })
              }else{
                addSameNode({
                  parentId:_this.selectedData.workPackId,
                  templateId:_this.templateId,
                  id:_this.selectedData.nodeId}).then((res)=>{
                  if(res){
                    _this.getWbsTemplate()
                  }
                  if(res.code=='200'){
                    _this.$message.success("新增成功")
                  }
                })
              }
            },
            onCancel() {
              console.log('Cancel');
            },
            class: 'test',
          });
        }
      },
      getPopupContainer(triggerNode){
        return  triggerNode.parentNode
      },
      // 新增下级节点
      addNextNode(){
        if(!this.selectedData){
          this.$message.error("请选择节点")
        }else{
          let _this = this
          this.$confirm({
            okText: '确定',
            cancelText: '取消',
            title: '确定新增下级节点?',
            onOk() {
              let list ={}
              if(_this.selectedData.nodeLevel=='1' || _this.selectedData.nodeLevel=='2' ){
                addNextNode({id:_this.selectedData.nodeId,templateId:_this.templateId}).then((res)=>{
                  if(res){
                    _this.getWbsTemplate()
                  }
                  if(res.code=='200'){
                    _this.$message.success("新增成功")
                    list = res.data
                  }
                })
                // values.id = `${new Date().getTime()}`
                // console.log(values)
                // gantt.addTask(this.valuesToTask(values),  this.selectedData.nodeId)
              }else{
                _this.$message.error("此节点不可新增下级节点")
              }
            },
            onCancel() {
              console.log('Cancel');
            },
            class: 'test',
          });
        }
      },
      handleSubmit() {
        this.confirmLoading = true
        this.form.validateFields((err, values) => {
          console.log(this.selectedData)
          if (!err) {
            console.log(values)
            this.addVisible = false
            const start = this.selectedData.start_date
            const duration = this.selectedData.duration
            const end = this.selectedData.start_date
            const parent = this.selectedData.parent
            values.start_date = start
            values.duration = duration
            values.text = ' '

            console.log(this.levelOption)
            let data = {}
            //新增同级节点
            if(this.levelOption===1){
              //如果选择的是一级节点
              console.log(this.selectedData.nodeLevel)
              if(this.selectedData.nodeLevel=='1'){
                // values.id = `${new Date().getTime()}`
                // console.log(values.id)
                // gantt.addTask(this.valuesToTask(values), parent)
                addSameNode({templateId:this.templateId,workPackId:this.selectedData.workPackId}).then((res)=>{
                  if(res){
                    this.getWbsTemplate()
                  }
                  if(res.code=='200'){
                    this.$message.success("新增节点成功")
                    this.resultData = res.data
                  }
                })
                // values.id = `${new Date().getTime()}`

                // console.log(values.id)
                // gantt.addTask(this.valuesToTask(values), parent)
                //如果选择的是二级节点

              } else if(this.selectedData.nodeLevel=='2'){
                // values.id = `${new Date().getTime()}`
                // console.log(values.id)
                // gantt.addTask(this.valuesToTask(values), parent)
                addSameNode({templateId:this.templateId,parentId:this.selectedData.nodeId}).then((res)=>{

                  if(res){
                    this.getWbsTemplate()
                  }
                  if(res.code=='200'){
                    this.$message.success("新增成功")
                  }
                })
                // values.id = `${new Date().getTime()}`
                // console.log(values.id)
                // gantt.addTask(this.valuesToTask(values), parent)
              }else{
                // values.id = `${new Date().getTime()}`
                // console.log(values.id)
                // gantt.addTask(this.valuesToTask(values), parent)
                addSameNode({
                  parentId:this.selectedData.workPackId,
                  templateId:this.templateId,
                  id:this.selectedData.nodeId}).then((res)=>{
                  if(res){
                    this.getWbsTemplate()
                  }
                  if(res.code=='200'){
                    this.$message.success("新增成功")
                  }
                })
              }
            }


            else if(this.levelOption===2){
              // 新增下级节点
              let list ={}
              if(this.selectedData.nodeLevel=='1' || this.selectedData.nodeLevel=='2' ){
                addNextNode({id:this.selectedData.nodeId,templateId:this.templateId}).then((res)=>{
                  if(res){
                    this.getWbsTemplate()
                  }
                  if(res.code=='200'){
                    this.$message.success("新增成功")
                    list = res.data
                  }
                })
                values.id = `${new Date().getTime()}`
                console.log(values)
                // gantt.addTask(this.valuesToTask(values),  this.selectedData.nodeId)
              }else{
                this.$message.error("此节点不可新增下级节点")
              }
            }
            const allTasks = gantt.getTaskByTime()
            this.tableData = this.dataListToTree(allTasks)
          }
        })
      },
      action(name) {
        // if('moveUp'===name){
        //   let _this = this
        //   let task_id = gantt.getSelectedId()
        //     _this.$refs.ganttCom.action(name)
        // }

        // 升级
        if('outdent'===name){
          if(!this.selectedData){
            this.$message.error("请选择节点")
          }else{
            let data={}
            if(this.selectedData.nodeLevel==1 || this.selectedData.nodeLevel==2){
              data ={
                templateId:this.templateId,
                positionTypeEnum:2,
                workPackId:this.selectedData.nodeId,
              }
            }else{
              data = {
                templateId:this.templateId,
                positionTypeEnum:2,
                workId:this.selectedData.nodeId,
              }
            }
            if(this.selectedData.nodeLevel=='1'){
              this.$message.error("不能升级")
            }else{
              editNode(data).then((res)=>{
                if(res){
                  this.getWbsTemplate()
                }
                if(res.code=='200'){
                  this.$message.success("升级成功")
                }
              })
            }
          }
        }

        // 降级
        if('indent'===name){
          if(!this.selectedData){
            this.$message.error("请选择节点")
          }else{
            let data={}
            if(this.selectedData.nodeLevel==1 || this.selectedData.nodeLevel==2){
              data ={
                templateId:this.templateId,
                positionTypeEnum:3,
                workPackId:this.selectedData.nodeId,
              }
            }else{
              data = {
                templateId:this.templateId,
                positionTypeEnum:3,
                workId:this.selectedData.nodeId,
              }
            }
            if(this.selectedData.nodeLevel=='3'){
              this.$message.error("不能降级")
            }else{
              editNode(data).then((res)=>{
                if(res){
                  this.getWbsTemplate()
                }
                if(res.code=='200'){
                  this.$message.success("降级成功")
                }
              })
            }
          }
        }

        // 上移
        if('moveUp'===name){
          if(!this.selectedData){
            this.$message.error("请选择节点")
          }else{
            let data={}
            if(this.selectedData.nodeLevel==1 || this.selectedData.nodeLevel==2){
              data ={
                templateId:this.templateId,
                positionTypeEnum:0,
                workPackId:this.selectedData.nodeId,
              }
            }else{
              data = {
                templateId:this.templateId,
                positionTypeEnum:0,
                workId:this.selectedData.nodeId,
              }
            }
            if(this.selectedData.nodeOrder=='0'|| this.selectedData.nodeOrder=='2'){
              this.$message.error("不能上移")
            }else{
              editNode(data).then((res)=>{
                if(res){
                  this.getWbsTemplate()
                }
                if(res.code=='200'){
                  this.$message.success("成功上移")
                  this.selectedData = res.data
                }else{

                }
              })
            }
          }
        }

        // 下移
        if('moveDown'===name){
          if(!this.selectedData){
            this.$message.error("请选择节点")
          }else{
            let data={}
            if(this.selectedData.nodeLevel==1 || this.selectedData.nodeLevel==2){
              data ={
                templateId:this.templateId,
                positionTypeEnum:1,
                workPackId:this.selectedData.nodeId,
              }
            }else{
              data = {
                templateId:this.templateId,
                positionTypeEnum:1,
                workId:this.selectedData.nodeId,
              }
            }
            if(this.selectedData.nodeOrder=='1'|| this.selectedData.nodeOrder=='2'){
              this.$message.error("不能下移")
            }else{
              editNode(data).then((res)=>{
                if(res){
                  this.getWbsTemplate()
                }
                if(res.code=='200'){
                  this.$message.success("下移成功")
                  this.selectedData = res.data
                }
              })
            }
          }
        }

        // 删除节点
        if ('del' === name) {
          let task_id = gantt.getSelectedId()
          // if (!task_id) {
          //   this.$message.warn('请先选择要删除的节点')
          //   return
          // }
          if(!this.selectedData){
            this.$message.warn('请选择节点')
          }else{
            if((this.tableData.length==1 && !this.tableData[0].children) || (this.tableData.length==1 && this.selectedData.nodeId==this.tableData[0].nodeId)){
              this.$message.error("不能删除")
            }else{
              let _this = this
              this.$confirm({
                okText: '删除',
                okType: 'danger',
                cancelText: '取消',
                title: '删除当前选择的节点?',
                onOk() {
                  let data = {}
                  if(_this.selectedData.nodeLevel==1 || _this.selectedData.nodeLevel==2){
                    data ={
                      workPackId:_this.selectedData.nodeId,
                      templateId:_this.templateId,
                    }
                  }else{
                    data = {
                      templateId:_this.templateId,
                      parentId:_this.selectedData.workPackId,
                      id:_this.selectedData.nodeId,
                    }
                  }
                  deleteNode(data).then((res)=>{
                    if(res){
                      _this.getWbsTemplate()
                    }
                    if(res.code=='200'){
                      this.$message.success("节点删除成功")
                      this.selectedData = res.data
                    }
                  })
                  // _this.$refs.ganttCom.action(name)
                },
                onCancel() {
                  console.log('Cancel');
                },
                class: 'test',
              });
            }
          }
        } else {
        }
        const allTasks = gantt.getTaskByTime()
        console.log(allTasks)
        this.tableData = this.dataListToTree(allTasks)
        console.log(this.tableData)
      },
      exportToPDFs() {
        gantt.exportToPDF({
          name: 'mygantt.pdf',
          header: '<h1>My company</h1>',
          footer: '<h4>Bottom line</h4>',
          locale: 'en',
          start: '01-04-2013',
          end: '11-04-2013',
          skin: 'terrace',
          data: {}
        })
      },
      addModal(task) {
        console.log(this.selectedTask)
        // if(this.selectedTask==null){
        //   this.$confirm({
        //     title: '提示！！',
        //     content: '请选中任务',
        //     okText: '确定',
        //     cancelText: '取消',
        //     onOk() {
        //       return false
        //     },
        //     onCancel() {
        //       return false
        //     },
        //   });
        //   return false
        // }
        this.confirmLoading = false
        const tasks = gantt.getTaskByTime()
        let parent = gantt.getSelectedId()

        // if(this.selectedTask.levelType==4){
        //   this.addvisible4 = true
        // }
        // if (task) {
        //   if (task.id) {
        //     this.preTasks = tasks.filter(t => t.id !== task.id)
        //     this.modalTitle = '编辑节点'
        //   } else {
        //     this.preTasks = tasks
        //     this.modalTitle = '新增节点'
        //   }
        //   this.form = this.$form.createForm(this, {})
        //   parent = task.parent
        // } else {
        //   this.preTasks = tasks
        //   this.modalTitle = '新增节点'
        //   this.form = this.$form.createForm(this, {})
        // }
        this.addVisible = true
        // if (task) {
        //   console.log(task)
        //   this.$nextTick(() => {
        //     this.taskType = task.type
        //     const period = [moment(task.start_date), moment(task.end_date)]
        //     this.form.setFieldsValue({
        //       id: task.id,
        //       name: task.name,
        //       period,
        //       level: task.level,
        //       type: task.type,
        //       duration: task.duration,
        //       parent: task.parent ? task.parent : ''
        //     })
        //   })
        // } else if (parent) {


        console.log(parent)
        // this.taskType = 'task'
        // this.$nextTick(() => {
        //   setTimeout(()=>{
        //     this.form.setFieldsValue({
        //       parent,
        //       type: 'task'
        //     })
        //   },0)
        // })
        // }
      },

      selectTask: function(task) {
        console.log('当前选中行数据:', task)
        this.selectedTask = task
        // gantt.selectTask(task.id);
      },
      deleteTask: function(taskId) {
        console.log('当前删除的数据：', taskId)
        this.selectedTask = task
        gantt.deleteTask(task.id);
      },
      addMessage(message) {
        // let _this = this
        // _this.messages.unshift(message)
        // if (_this.messages.length > 40) {
        //   _this.messages.pop()
        // }
      },
      logTaskUpdate(id, mode, task) {
        const text = (task && task.text ? ` (${task.text})` : '')
        const message = `Task ${mode}: ${id} ${text}`
        this.addMessage(message)
      },
      rowClassNames(record){
        if( this.selectId == record.nodeId ){
          return 'clickRowStyle'
        }
      },
      logLinkUpdate(id, mode, link) {
        let message = `Link ${mode}: ${id}`
        if (link) {
          message += ` ( source: ${link.source}, target: ${link.target} )`
        }
        this.addMessage(message)
      }
    }
  }
</script>

<style scoped>
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  /deep/ .ant-table-body  .clickRowStyle{
    background-color: rgb(230, 243, 252);
  }
  /deep/ .ant-pro-basicLayout-children-content-wrap{
    flex:1;
  }
  .gantt-layout{
    position: relative;
  }
  /deep/ .ant-table-thead th{
    height: 60px;
    line-height: 60px;
    padding: 0;
  }
  /deep/ .ant-table-placeholder{
    height: 600px;
  }
  /deep/ .gantt-layout .ant-table-body{
    min-height: 600px;
  }
  /deep/ .ant-drawer-content-wrapper{
    box-shadow: none !important;
  }
  /deep/ .ant-table-selection-column{
    width:40px;
  }

  .button-bar {
    margin-bottom: 10px;
  }

  .button-bar > button:not(:first-child) {
    margin-left: 10px;
  }
  /deep/ .ant-modal-body{
    padding:0
  }

  td{
    display:flex;
  }
  /* /deep/ .ant-select:not(.ant-pagination-options-size-changer) .ant-select-selection, .ant-input-number{
    height:100% !important;
    width:100px !important
} */
  input[type='text'], input[type='password'], input[type='number'], textarea {
      width:100%;height:28px
  }
.ant-calendar-picker{
    width:200px;height:28px
}
.ant-cascader-picker{
    width:100%;height:28px
}
form .ant-select, form .ant-cascader-picker{
    width:100%;height:28px
}
.ant-calendar-picker-input.ant-input{
    width:200px;height:28px
}
.total div{
  padding:0 5px
}
</style>
